package com.example.gridlayoutdemo08.view;

import android.animation.LayoutTransition;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.DragEvent;
import android.view.Gravity;
import android.view.View;
import android.widget.GridLayout;
import android.widget.TextView;

import com.example.gridlayoutdemo08.R;

import java.util.List;

/**
 * Created by wanghao on 2016/5/25.
 * 它需要向外提供一个setItems方法,传递String集合进来,我们直接创建界面
 * 提供一个setAllowDrag方法,设置是否允许拖拽
 */
public class DragGridLayout extends GridLayout {
    private final int columnCount=4;//设置列数
    private boolean mallowDrag;//记录是否可以进行拖拽
    private Rect[] mRects;//每个子控件的矩形数组
    private TextView dragedView;//被拖拽的文本
    private OnClickItemListener mOnClickItemListener;

    public DragGridLayout(Context context) {
        this(context,null);
    }

    public DragGridLayout(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public DragGridLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
//        android:columnCount="4"
//        android:animateLayoutChanges="true"
        this.setColumnCount(columnCount);
        this.setLayoutTransition(new LayoutTransition());
    }
    public void setItems(List<String> items){
        this.removeAllViews();
        for (String item:items) {
            addItem(item);
        }
    }

    private View.OnLongClickListener olcl = new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            /*第一个参数与第三个参数用来传递数据和状态,给null
            第二个参数用来创建拖拽阴影
            第四个参数,未定义给0*/
            dragedView = (TextView) v;

            v.startDrag(null,new View.DragShadowBuilder(v),null,0);
           // v.setEnabled(false);//变红虚线
            return true;
        }
    };
    public void addItem(String item) {
        TextView tv = newItemTextView();
        tv.setText(item);
        if (mallowDrag){
            tv.setOnLongClickListener(olcl);
        }else {
            tv.setOnLongClickListener(null);
        }
        this.addView(tv);
    }

    //创建对应的文本
    private TextView newItemTextView() {
        //给gridlayout添加子控件
        TextView tv = new TextView(getContext());
        int margin = 5;
        GridLayout.LayoutParams params = new GridLayout.LayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels/
                columnCount-2*margin;
        params.height = GridLayout.LayoutParams.WRAP_CONTENT;
        tv.setGravity(Gravity.CENTER);//设置文字居中
        //params.setGravity(Gravity.CENTER);
        params.setMargins(margin,margin,margin,margin);
        tv.setLayoutParams(params);
        tv.setBackgroundResource(R.drawable.tv_bg);

        tv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnClickItemListener != null){
                    mOnClickItemListener.onClickItem((TextView) v);
                }
            }
        });
        return tv;
    }
    public void setAllowDrag(boolean allowDrag){
        this.mallowDrag = allowDrag;
        if (this.mallowDrag){
            this.setOnDragListener(odl);
        }
    }
    private View.OnDragListener odl = new View.OnDragListener() {
        //当前接收拖拽事件的视图对象:gridlayout
        @Override
        public boolean onDrag(View v, DragEvent event) {
            switch (event.getAction()){
                case DragEvent.ACTION_DRAG_STARTED:
                    if(dragedView != null){
                        dragedView.setEnabled(false);
                    }
                    //在开始拖拽的时候,定义出每个子控件的矩形数组
                    initRects();
                    break;
                case DragEvent.ACTION_DRAG_LOCATION:
                    //实时判断手指是否进入了子控件范围内
                    int touchIndex = getTouchIndex(event);
                    if (touchIndex>-1 && dragedView !=null && dragedView != DragGridLayout.this.getChildAt(touchIndex)){
                        DragGridLayout.this.removeView(dragedView);
                        DragGridLayout.this.addView(dragedView,touchIndex);
                    }
                    break;
                case DragEvent.ACTION_DRAG_ENDED:
                    if(dragedView != null){
                        dragedView.setEnabled(true);
                    }
                    break;
            }
            return true;
        }
    };
    //定义出每个子控件的矩形数组
    private void initRects() {
        mRects = new Rect[this.getChildCount()];
        for (int i = 0;i<this.getChildCount();i++){
            View childView = this.getChildAt(i);
            mRects[i] = new Rect(childView.getLeft(),childView.getTop(),childView.getRight(),
                    childView.getBottom());
        }
    }
    //实时判断手指是否进入了子控件范围内
    private int getTouchIndex(DragEvent event) {
        for (int i =0; i<mRects.length;i++){
            if (mRects[i].contains(((int)event.getX()),((int)event.getY()))){
                return i;
            }
        }
        return -1;
    }
    public void setOnClickItemListener(OnClickItemListener listener) {
        this.mOnClickItemListener = listener;
    }

    //用来点击的时候将对应的文本返回主界面
    public interface OnClickItemListener{
        public void onClickItem(TextView tv);
    }
}
